package org.video.mine.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import org.video.mine.HomeDocModel;
import org.video.mine.R;
import org.video.mine.Urls;
import org.video.mine.adapter.TvOtherAdapter;
import org.video.mine.databinding.ActivitySearchBinding;
import org.video.mine.entity.DongHuaEntity;
import org.video.mine.network.JsoupGet;
import org.video.mine.utils.Progress;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {

    private ActivitySearchBinding binding;
    private Context context;
    private List<DongHuaEntity> adapterLists = new ArrayList<>();
    private TvOtherAdapter searchAdapter;
    private HomeDocModel homeDocModel;
    private int page=1;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    if (adapterLists.size()==0){
                        binding.srf.setVisibility(View.GONE);
                    }else {
                        binding.srf.setVisibility(View.VISIBLE);
                    }
                    progress.dismiss();
                    searchAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    Toast.makeText(context,"没有更多了..",Toast.LENGTH_SHORT).show();
                    binding.srf.finishLoadMore();
                    break;
            }
        }
    };
    private ViewModelStoreOwner owner;
    private String searchText="";
    private Progress progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search);
        setContentView(binding.getRoot());
        context = this;
        owner = this;
        homeDocModel = new ViewModelProvider(this).get(HomeDocModel.class);

        progress = new Progress(context);
        homeDocModel.searchPages = -1;
        initView();
    }

    private void initView() {
        if (adapterLists.size()==0){
            binding.srf.setVisibility(View.GONE);
        }else {
            binding.srf.setVisibility(View.VISIBLE);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context,1);
        binding.cyclerView.setLayoutManager(gridLayoutManager);
        searchAdapter = new TvOtherAdapter(adapterLists, context, "donghua");
        binding.cyclerView.setAdapter(searchAdapter);

        binding.srf.setEnableRefresh(false);
        binding.srf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                if (homeDocModel.searchPages==-1){
                    page--;
                    mHandler.sendEmptyMessage(1);
                }else {
                    initData();
                }
            }
        });

        binding.rlSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
                        hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                if (!binding.etSearch.getText().toString().equals(searchText) || adapterLists==null || adapterLists.size()==0){
                    adapterLists.clear();
                    page = 1;
                    searchText = binding.etSearch.getText().toString();
                    progress.show();
                    initData();
                }
            }
        });

        binding.etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
                            hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    if (!binding.etSearch.getText().toString().equals(searchText) || adapterLists==null || adapterLists.size()==0){
                        adapterLists.clear();
                        page = 1;
                        searchText = binding.etSearch.getText().toString();
                        progress.show();
                        initData();
                        return true;
                    }
                    return false;
                }
                return false;
            }
        });
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<DongHuaEntity> search;
                try {
                    search = JsoupGet.getSearch(owner, Urls.searchUrl, URLEncoder.encode(searchText,"UTF-8"), page);
                    if (adapterLists==null || binding.srf==null)
                        return;
                    adapterLists.addAll(search);
                    mHandler.sendEmptyMessage(0);
                    binding.srf.finishLoadMore();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("顺序：","searchPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("顺序：","searchStop");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("顺序：","searchResume");
    }
}
